package com.community.sqlapp.controller;

import com.community.sqlapp.service.DatabaseService;
import com.community.sqlapp.service.QianwenService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequiredArgsConstructor
public class SqlController {
    
    private final DatabaseService databaseService;
    private final QianwenService qianwenService;
    
    @GetMapping("/")
    public String index(Model model) {
        try {
            List<String> tables = databaseService.getAllTables();
            System.out.println("控制器获取到的表: " + tables);
            model.addAttribute("tables", tables);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "获取表失败: " + e.getMessage());
        }
        return "index";
    }
    
    @GetMapping("/table/{tableName}")
    @ResponseBody
    public List<Map<String, Object>> getTableStructure(@PathVariable String tableName) {
        System.out.println(databaseService.getTableStructure(tableName).get(0));
        return databaseService.getTableStructure(tableName);

    }
    
    @PostMapping("/execute")
    @ResponseBody
    public Map<String, Object> executeQuery(@RequestBody Map<String, String> request) {
        String sql = request.get("sql");
        return databaseService.executeQuery(sql);
    }
    
    @PostMapping("/generate")
    @ResponseBody
    public Map<String, String> generateSql(@RequestBody Map<String, Object> request) {
        Map<String, String> response = new HashMap<>();
        try {
            String prompt = (String) request.get("prompt");
            List<String> selectedTables = (List<String>) request.get("tables");

            // 获取表结构信息
            Map<String, List<Map<String, Object>>> tablesInfo = new HashMap<>();
            for (String tableName : selectedTables) {
                List<Map<String, Object>> tableStructure = databaseService.getTableStructure(tableName);
                tablesInfo.put(tableName, tableStructure);
            }

            // 调用API生成SQL
            String generatedSql = qianwenService.generateSql(prompt, tablesInfo);
            response.put("sql", generatedSql);

        } catch (Exception e) {
            e.printStackTrace();
            // 返回更友好的错误信息
            response.put("sql", "-- 生成SQL时出错: " + e.getMessage() + "\n请尝试简化您的查询需求。");
        }
        return response;
    }
} 